#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#define ERROR_CHECK(ret, funcName) \
do{ \
    if(ret != 0) \
    { \
        printf("%s : %s \n", funcName, strerror(ret));\
        exit(1); \
    } \
}while(0);

void *threadFunc(void *arg)
{
    //此时子线程让出了CPU控制权，子线程在睡觉
    usleep(100);

    printf("I'm child thread\n");
    int *pInt = (int *)arg;
    printf("*pInt = %d\n", *pInt);

    printf("child thread id: %ld\n", pthread_self());
    //让子线程主动退出
    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    pthread_t thid;
    int number = 100;
    int ret = pthread_create(&thid, NULL, threadFunc, &number);
    ERROR_CHECK(ret, "pthread_create");
    printf("child thread id: %ld\n", thid);

    //线程的执行是随机的
    printf("I'm main thread\n");
    printf("main thread id: %ld\n", pthread_self());

    //让主线程将子线程取消(杀死)
    ret = pthread_cancel(thid);
    ERROR_CHECK(ret, "pthread_cancel");

    //让主线程阻塞等待子线程的执行
    ret = pthread_join(thid, NULL);
    ERROR_CHECK(ret, "pthread_join");

    return 0;
}



